<template>
  <div>
    <el-card>
      <!-- 顶部面包屑标识与导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
        <el-breadcrumb-item :to="{ path: '/' }">
          <i class="el-icon-s-promotion"></i> 后台管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>类别管理</el-breadcrumb-item>
        <el-breadcrumb-item v-for="item in history" :key="item.id"><span v-text="item.name"></span></el-breadcrumb-item>
      </el-breadcrumb>
      <el-divider></el-divider>
      <el-row  style="margin-top: 10px">
        <el-button type="primary" @click="openAddNewDialog()" style="margin-left: 10px">新增</el-button>
        <download-excel
            style="float: left"
              class="export-excel-wrapper"
              :data="categoryData"
              type="xls"
              worksheet="worksheet"
              name="用户信息">
            <el-button type="primary">导出</el-button>
        </download-excel>
      </el-row>
      <el-table
          :data="categoryData"
          style="width: 100%">
        <el-table-column
            prop="id"
            label="类别编号"
            width="180">
        </el-table-column>
        <el-table-column
            prop="name"
            label="类别名称"
            width="180">
        </el-table-column>
        <el-table-column
            align="center"
            prop="categoryLevel"
            label="层级">
        </el-table-column>
        <el-table-column
            align="center"
            prop="isParent"
            label="子级类别">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="scope.row.isParent == 0"
                       @click="showSubCategoryList(scope.row)">查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="200px"
                         align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="mini"
                       @click="openEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini"
                       @click="openDeleteConfirm(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 返回上层 -->
      <div v-if="currentParentId != 0" style="margin-top: 10px; text-align: right;">
        <el-button size="small" @click="goBack()">返回</el-button>
      </div>
      <!-- 新增类别的表单 -->
      <el-dialog title="新增类别" :visible.sync="addNewFormVisible">
        <el-form :model="newForm" :rules="editRules" label-width="120px">
          <el-form-item label="父级类别" prop="typeId">
            <el-cascader
                v-model="newForm.parentId"
                :options="categoryDataOptions"
                :props="{checkStrictly: true}"
                clearable="true"
                @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="类别名称" prop="name">
            <el-input v-model="newForm.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addNewFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="AddNewDialog()">确 定</el-button>
        </div>
      </el-dialog>
      <!--   修改类别的表单     -->
      <el-dialog title="修改类别" :visible.sync="editFormVisible">
        <el-form :model="editForm" :rules="editRules" label-width="120px">
          <el-form-item label="父级类别" prop="typeId">
            <el-cascader
                v-model="editForm.parentId"
                :placeholder="editForm.parentName"
                :options="categoryDataOptions"
                :props="{checkStrictly: true}"
                clearable="true"
                @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="类别名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEdit">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Category",
  data() {
    return {
      /*存放游览子级的历史*/
      history:[],
      // 当前类别列表的父级类别ID
      currentParentId: 0,
      // 标签类别的下拉菜单的选择列表
      categoryDataOptions: [],
      // 编辑对话框相关数据
      editFormVisible: false,
      addNewFormVisible:false,
      newForm: {
        parentId: '0',
        name: '',
      },
      editForm: {
        parentId: '',
        name: '',
      },
      // 编辑表单规则
      editRules: {
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'}
        ],
      },
      category:{},
      // 表格数据
      categoryData: [],

    }
  },
  methods: {
    // 返回
    goBack() {
      console.log('goBack, start...');
      console.log(this.history.length)
      let parentCategory = this.history[this.history.length - 1];
      console.log(this.history[this.history.length-1])
      this.currentParentId = parentCategory.parentId;
      console.log(parentCategory)
      this.loadCategoryList();
      this.history.pop();

      console.log('goBack, done.');
      for(let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')
    },
    /*查看子级类别*/
    showSubCategoryList(category){
      this.history[category.categoryLevel -1] = category;
      console.log('showSubCategoryList');
      for(let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')

      this.currentParentId = category.id;
      this.loadCategoryList()
    },
    handleChange(value) {
      console.log(value);
    },
    // 打开编辑对话框
    openEditDialog(row) {
      console.log(row)

      let url = 'http://localhost:8080/v1/category/getById?id=' +row.id;
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response)=>{
            if(response.data.code==1){
              this.editForm = response.data.data;
              console.log(this.editForm)
            }else{
              this.$message.error(response.data.msg)
            }
      })
      this.loadCategoryTreeList();
      this.editFormVisible = true

    },
    handleEdit(){
      if(Array.isArray(this.editForm.parentId)){
        this.editForm.parentId = this.editForm.parentId.pop();
      }

      let url = 'http://localhost:8080/v1/category/update';
      console.log(url)
      let formdata = this.qs.stringify(this.editForm)
      console.log(formdata)
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url,formdata).then((response)=>{
            if (response.data.code==1){
              this.$message.success("修改成功!")

            }else{
              this.$message.error(response.data.msg)
            }
        this.editFormVisible = false;
            location.reload();
      })
    },
    // 打开新增对话框
    openAddNewDialog(category) {
      this.loadCategoryTreeList();
      this.addNewFormVisible = true

    },
    AddNewDialog(){
      let url = 'http://localhost:8080/v1/category/addNew';
      console.log('url = ' + url);
      if (Array.isArray(this.newForm.parentId)) {
        this.newForm.parentId = this.newForm.parentId.pop();
      }
      if(this.newForm.parentId<0){
        this.newForm.parentId = 0;
      }

      let formData = this.qs.stringify(this.newForm);
      console.log('formData = ' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url,formData).then((response)=>{
        if(response.data.code==1){
          this.$message.success("添加成功！")
          this.addNewFormVisible = false
          return
        }else{
          this.$message.success(response.data.msg);
        }

      })
    },
    // 打开删除确认框
    openDeleteConfirm(category) {
      let message = '此操作将永久删除【' + category.name + '】用户，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(category);
      }).catch(() => {
      });
    },
    // 处理删除
    handleDelete(category) {
      let url = 'http://localhost:8080/v1/category/' + category.id + '/delete';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.code == 1) {
          this.$message({
            message: '删除【' + category.name + '】类别成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else {
          this.$message.error(jsonResult.msg)
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadCategoryList();
    },
    // 加载类别列表
    loadCategoryList() {
      let url = 'http://localhost:8080/v1/category/listByParentId?parentId=' + this.currentParentId;
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.code === 1) {
          this.categoryData = jsonResult.data;
          this.categoryDataOptions = jsonResult.data;
          console.log(jsonResult.data)
        }else{
          this.$message.error(jsonResult.msg)
        }
      })
    },
    loadCategoryTreeList() {
      let url = 'http://localhost:8080/v1/category/tree/?id=0';

      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.code === 1) {
          this.categoryDataOptions = jsonResult.data;
          console.log(jsonResult.data.list)
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    }
  },
  mounted() {
    this.loadCategoryList();
  }
}
</script>

<style scoped>

</style>